//
//  TYDataManager.m
//  TravelYo
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 TravelYo. All rights reserved.
//

#import "TYDataManager.h"
#import "Reachability.h"

@implementation TYDataManager

// 单例初始化方法
+ (instancetype)shareManager
{
    static TYDataManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[[self class] alloc] init];
    });
    return manager;
}

// 解析数据
- (void)requestDataWithUrl:(NSString *)url block:(void(^)())block
{
    
    // 开启网络链接
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    // 开启一个通知 来监听网络状态的改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    // 开启网络监控
    [reach startNotifier];
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSURL *Url = [NSURL URLWithString:url];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:Url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
        [request setHTTPMethod:@"GET"];
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                block(data);
            });
        }];
        [dataTask resume];
    });

    
    
}


- (void)reachabilityChanged:(NSNotification *)changed
{
    /*
     网络是否链接 -- isReachable
     WiFi ---- isReachableViaWiFi
     2G,3G --- isReachableViaWWAN
     */
    // 获取 View 里开启的哪个网络连接
    Reachability *reach = [changed object];
    if (![reach isReachable]) {
       // NSLog(@"网络不可用");
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"本软件需要联网" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alert dismissWithClickedButtonIndex:0 animated:YES];
        });
       
        [alert show];
        
    } else {
        if (reach.isReachableViaWiFi) {
            
            // NSLog(@"当前WiFi链接");
            
        } else if (reach.isReachableViaWWAN) {
            
           //  NSLog(@"当前 2G, 3G 链接");
            
        }
    }
    
    
}


@end
